package cn.lili.modules.message.serviceimpl;

import cn.lili.common.vo.PageVO;
import cn.lili.exchange.AmqpExchangeProperties;
import cn.lili.modules.message.entity.dos.Message;
import cn.lili.modules.message.entity.vos.MessageVO;
import cn.lili.modules.message.mapper.MessageMapper;
import cn.lili.modules.message.service.MessageService;
import cn.lili.mybatis.util.PageUtil;
import cn.lili.routing.MsgRoutingKey;
import cn.lili.util.AmqpMessage;
import cn.lili.util.AmqpSender;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 管理端发送消息内容业务层实现
 *
 * @author Chopper
 * @since 2020/11/17 3:48 下午
 */
@Service
@RequiredArgsConstructor
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    private final AmqpSender amqpSender;

    private final AmqpExchangeProperties amqpExchangeProperties;

    @Override
    public Page<Message> getPage(MessageVO messageVO, PageVO pageVO) {
        return this.page(PageUtil.initPage(pageVO), messageVO.lambdaQueryWrapper());
    }


    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public Boolean sendMessage(Message message) {
        //保存站内信信息
        this.save(message);

        amqpSender.send(
                AmqpMessage.builder()
                        .exchange(amqpExchangeProperties.getMsg())
                        .routingKey(MsgRoutingKey.MESSAGE)
                        .message(message)
                        .build()
        );

        return true;
    }

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public Boolean deleteMessage(String id) {
        //只有查询到此记录才真实删除，未找到记录则直接返回true即可
        Message message = this.getById(id);
        if (message != null) {
            return this.removeById(id);
        }
        return true;
    }
}